<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="归属" value="1"></el-option>
              <el-option label="批次" value="2"></el-option>
              <el-option label="应用名" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="labelTable" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="110" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="80" align="center" prop="batch" label="SN码批次"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="80" align="center" prop="app_name" label="应用名"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="180" align="center" prop="content" label="限制ID">
        <template slot-scope="scope">
          <div class="flex flex_cen flex-wrap">
            <div v-for="(item,index) in scope.row.content.split(',')" :key="index" style="width:50%">{{item}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="130" align="center" prop="desc" label="说明"></el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdAppInside(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getdeleteAppInside(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize"></el-pagination>
    </div>
    <!-- 隐藏 -->
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog :title="!redactDisabled  ? '应用内部广告管控' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
        <div class="hintText">
          <ul>
            <li>获取应用的限制ID，请与管理员联系</li>
          </ul>
        </div>
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <el-form-item label="SN码批次:" label-width="100px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="没有选中任何项" class="add_select" :disabled="redactDisabled" @change="batchChange">
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用名" label-width="100px" prop="app_name">
            <el-select v-model="addForm.app_name" placeholder="请先选择批次" class="add_select" :disabled="packagetDisabled" @change="appNameChange">
              <el-option v-for="(item,index) in AppPackage" :key="index" :label="item.app_name" :value="item.app_name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="包名:" label-width="100px" prop="package">
            <el-select v-model="addForm.package" placeholder="请先选择应用名" class="add_select">
              <el-option v-for="item in apptions" :key="item.id" :label="item.app_package" :value="item.app_package"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="限制ID" label-width="100px" prop="content" v-for="(domain) in addForm.content" :key="domain.key">
            <div class="addPut">
              <el-input v-model="domain.value" class="add_select" placeholder="请输入限制ID" :maxlength="30"></el-input>
              <el-button class="dlePut btnLocation" size="mini" icon="el-icon-delete" @click.prevent="removeDomain(domain)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="100px">
            <el-button type="primary" @click="addDomain" icon="el-icon-upload" size="mini" round>增加</el-button>
          </el-form-item>
          <el-form-item label="说明" label-width="100px" prop="desc">
            <el-input v-model="addForm.desc" class="add_select" placeholder="请输入说明,最多32位" maxlength="32"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="!redactDisabled" type="primary" @click="getaddAppInside('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click="geteditAppInside('ruleForm')" size="mini" round>编辑</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 模板操作图片弹窗 -->
    <div class="component" v-if="imgShow">
      <div class="mbImg"><img src="@/assets/images/snNbgk.png" alt=""></div>
      <div class="masking" @click="imgShow = false"></div>
    </div>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryAppInside, queryIdAppInside, queryNameApp, deleteAppInside, addAppInside, AppPackage, editAppInside } from "@/api/deployment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "SN码批次", "应用名", "限制ID", "说明", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      total: 0,
      searchTable: "",
      select: "2", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制 
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //批次下拉选择
      lotoptions: [],
      //包名下拉选择
      apptions: [],
      //编辑禁用控制,
      //应用名下拉选择
      AppPackage: [],
      redactDisabled: false,
      packagetDisabled: true,
      labelTable: [],
      //添加表单
      addForm: { content: [{ value: '' }], desc: "", app_name: '', package: "", batch: '' },
      rules: {
        content: [{ required: true, message: "请输入限制ID", trigger: "blur" }],
        app_name: [{ required: true, message: "请输入应用名", trigger: "blur" }],
        package: [{ required: true, message: "请选择包名", trigger: "blur" }],
        batch: [{ required: true, message: "请选择批次", trigger: "blur" }]
      },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, batch: undefined, app_name: undefined },
      imgShow: false,
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 }
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryAppInside()
    this.getBatchTwos()
  },
  methods: {
    //删除
    getdeleteAppInside(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteAppInside(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAppInside()
      })
    },
    //表单动态添加input
    removeDomain(item) {
      var index = this.addForm.content.indexOf(item)
      if (index !== -1) {
        this.addForm.content.splice(index, 1)
      }
    },
    addDomain() {
      if (this.addForm.content == 50) return this.$message({ type: 'warning', message: '限制50条数' })
      this.addForm.content.push({ value: '', key: Date.now() });
    },
    //根据ID获取包名信息
    getAppPackage(bId) {
      let data = { userId: localStorage.getItem("ID"), bId: bId }
      AppPackage(data).then(res => {
        this.AppPackage = res.data
        console.log('获取包名', res.data)
      }).catch(err => {
        this.AppPackage = []
      })
    },
    //添加应用内部管控
    getaddAppInside(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.content = this.addForm.content.map(item => item.value).toString()
          addForm.batch = this.addForm.batch
          addAppInside(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryAppInside()
            this.dialogFormVisible = false
          }).catch(err => {})
        } else {
          return false;
        }
      });
    },
    //批次change事件
    batchChange(val) {
      this.getAppPackage(val)
      this.packagetDisabled = false
    },
    //输入应用名查询包名
    appNameChange(value) {
      let data = { userId: localStorage.getItem("ID"), app_name: value }
      this.addForm.package = ''
      queryNameApp(data).then(res => {
        this.apptions = res.data
        console.log('成功', res)
      }).catch(err => {
        this.apptions = []
      })
    },
    //根据ID获取应用内部页面管控
    getqueryIdAppInside(id) {
      this.redactDisabled = true
      this.packagetDisabled = false
      this.editSubjects = false
      this.subjectId = id
      queryIdAppInside({ id: id }).then(({ data }) => {
        this.dialogFormVisible = true
        Object.keys(this.addForm).forEach(key => this.addForm[key] = data[key])
        this.addForm.content = data.content.split(',').map(item => { return { 'value': item } })
        this.getAppPackage(data.batch)
        console.log('获取信息', data,)
      })
    },
    //编辑应用内部页面管控
    geteditAppInside(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          addForm.batch = this.addForm.batch.toString()
          addForm.content = this.addForm.content.map(item => item.value).toString()
          addForm.batch = this.addForm.batch.split(',')[0]
          editAppInside(addForm).then(res => {
            this.dialogFormVisible = false
            this.$message.success(res.msg)
            this.getqueryAppInside()
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    getqueryAppInside() {
      queryAppInside(this.listQuery).then(res => {
        this.labelTable = res.data
        this.total = res.total
      }).catch(err => {
        this.labelTable = []
        this.total = 0
      })
    },
    //搜索,1：包名，2:批次
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.username = this.searchTable
          break;
        case '2':
          this.listQuery.batch = this.searchTable
          break;
        case '3':
          this.listQuery.app_name = this.searchTable
          break;
      }
      this.getqueryAppInside();
    },
    btnaddBrand() {
      this.redactDisabled = false
      this.packagetDisabled = true
      this.dialogFormVisible = true
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAppInside();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAppInside();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), username: undefined, batch: undefined, app_name: undefined }
      this.getqueryAppInside()
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = { content: [{ value: '' }], desc: "", app_name: '', package: "", batch: '' }
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style scoped>
/deep/ .el-dialog__body {
  padding-top: 0;
}
/deep/ .el-dialog__header {
  transform-origin: 50% 100%;
  border-bottom: 0.5px solid #e9e9e9;
}
</style>